# -*- coding: UTF-8 -*-
# svn 命令行大全
import subprocess

from enum import Enum


class Shell(Enum):
    SVN_CHECK = 'svn'
    SVN_CHECKOUT = 'svn checkout'
    SVN_UPDATE = 'svn update'
    SVN_COMMIT = 'svn commit'
    SVN_CHECKOUT_EMPTY = "svn co --depth=empty"
    SVN_UP = "svn up"
    SVN_STATUS = "svn status"
    SVN_ADD = "svn add"


class Command:
    def __init__(self):
        self.command = Shell

    def add(self, path: str):
        return self.__private_exc(self.command.SVN_ADD.value, path)

    def status(self, _path: str):
        shell = self.command.SVN_STATUS.value + " "
        res = None
        try:
            res = subprocess.check_output(shell, shell=True, text=True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT,
                                          cwd=_path)
        except subprocess.CalledProcessError as e:
            pass
        return res

    # TODO 提交 path
    # svn commit -m "commit message"
    def commit(self, path, msg):
        return self.__private_exc(self.command.SVN_COMMIT.value + ' ' + path, ' -m "' + msg + '"')

    def update(self, path):
        self.__private_exc(self.command.SVN_UPDATE.value, path, True)

    def __private_exc(self, _cmd, path, isForce=False):
        force = ''
        if isForce:
            force = '--force'
        shell = _cmd + ' ' + path + ' ' + force
        res = None
        try:
            res = subprocess.check_output(shell, shell=True, text=True)
        except subprocess.CalledProcessError as e:
            print(f"svn 命令错误 {e}")
        return res

    # TODO: 远程地址 work_path:本地路径，_list 请求文件列表csd/csb call（进度回调） finish_call 完成回调
    def checkout(self, url, work_path, _list, call, finish_call):
        shell = self.command.SVN_CHECKOUT_EMPTY.value + " " + url
        self.__private_exc(shell, work_path, True)  # 创建好本地仓库后
        size = len(_list)
        i = 0
        for every in _list:
            sell_cmd = self.command.SVN_UPDATE.value + " " + every
            try:
                res = subprocess.check_output(sell_cmd, timeout=6000, shell=True, stdin=subprocess.PIPE,
                                              text=True,
                                              cwd=work_path)
                i += 1
                if call is not None:
                    call(res, every, i, size)
                if size == i and finish_call is not None:
                    finish_call(res, True, i)  # 完成后回调
            except subprocess.CalledProcessError or NotADirectoryError as err:
                i = 0
                if finish_call is not None:
                    finish_call("异常终止", False, i)
